#!/bin/bash

# 硬编码配置文件路径
CONFIG_FILE="/home/argo/catkin_ws/src/rads-master/config/params.yaml"

# 参数检查
if [ $# -ne 2 ]; then
  echo "Usage: $0 <parameter_name> <new_value>"
  exit 1
fi

PARAM_NAME=$1
RAW_VALUE=$2

# 智能判断值类型函数
function process_value() {
  local val=$1
  
  # 如果是数字（整数或小数）
  if [[ $val =~ ^-?[0-9]+(\.[0-9]+)?$ ]]; then
    echo "$val"
  # 如果是布尔值
  elif [[ $val =~ ^(true|false|TRUE|FALSE)$ ]]; then
    echo "$val"
  # 如果已经是带引号的字符串
  elif [[ $val =~ ^\".*\"$ ]] || [[ $val =~ ^\'.*\'$ ]]; then
    echo "$val"
  # 其他情况视为字符串并加双引号
  else
    echo "\"$val\""
  fi
}

PROCESSED_VALUE=$(process_value "$RAW_VALUE")

# 执行修改（兼容GNU和BSD sed）
if sed --version 2>&1 | grep -q GNU; then
  sed -i -E "/^[[:space:]]*${PARAM_NAME}[[:space:]]*:/ {
    s|:[[:space:]]*([^#[:space:]]*)[[:space:]]*(#.*)?|: ${PROCESSED_VALUE} \2|
    t
    s|:[[:space:]]*|: ${PROCESSED_VALUE} |
  }" "$CONFIG_FILE"
else
  sed -i '' -E "/^[[:space:]]*${PARAM_NAME}[[:space:]]*:/ {
    s|:[[:space:]]*([^#[:space:]]*)[[:space:]]*(#.*)?|: ${PROCESSED_VALUE} \2|
    t
    s|:[[:space:]]*|: ${PROCESSED_VALUE} |
  }" "$CONFIG_FILE"
fi

echo "Config updated: ${PARAM_NAME} = ${PROCESSED_VALUE}"
